package com.autumn.context.utils;

import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author niann
 * @description
 * @date 2023/12/20 20:59
 */
public class YamlUtils {

    public static Map<String, Object> loadYaml(String path) {
        Yaml yaml = new Yaml();
        try {
            try (FileInputStream fileInputStream = new FileInputStream(path)) {
                Map<String, Object> map = yaml.load(fileInputStream);
                return build(map);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    private static Map<String, Object> build(Map<String, Object> map) {
        ConcurrentHashMap<String, Object> concurrentHashMap = new ConcurrentHashMap<>(map);
        concurrentHashMap.forEach((k, v) -> {
            if (v instanceof Map) {
                ((Map<?, ?>) v).forEach((k2, v2) -> {
                    String key = "%s.%s".formatted(k, k2);
                    if (v2 == null) {
                        throw new RuntimeException("application.yaml:{%s} The field cannot be empty".formatted(key));
                    }
                    if (v2 instanceof Integer) {
                        map.put(key, String.valueOf(v2));
                    } else if (v2 instanceof Boolean) {
                        map.put(key, String.valueOf(v2));
                    } else {
                        map.put(key, v2);
                    }
                    map.remove(k);
                    build(map);
                });
            }
        });
        return map;
    }
}
